package com.corecmd.tcloud.tcimserver.controller;

import com.corecmd.tcloud.tcimserver.domain.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote :
 * @date : 2021/2/26
 * @copyright :
 */
@Slf4j
public class BaseController {
    /**
     * 根据Token取得用户信息
     * @return
     */
    public UserInfoDTO getTokenUser(String authToken, HttpServletRequest request, HttpServletResponse response){
        UserInfoDTO tokenUser = null;
        try {
            SessionKey sessionKey = new DefaultSessionKey(authToken);
            Session session = SecurityUtils.getSecurityManager().getSession(sessionKey);
            String loginRoleId = (String) session.getAttribute("loginRoleId");
            Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
            if (null != coll){
                tokenUser = (UserInfoDTO) coll.getPrimaryPrincipal();
                tokenUser.setAuthToken(authToken);
            }
        } catch (Exception e) {
            log.info("根据token获取用户信息异常",e);
        }
        return tokenUser;
    }
    /**
     * 根据Token取得用户信息
     * @return
     */
    public UserInfoDTO validateToken(String authToken){
        UserInfoDTO tokenUser = null;
        try {
            SessionKey sessionKey = new DefaultSessionKey(authToken);
            Session session = SecurityUtils.getSecurityManager().getSession(sessionKey);
            String loginRoleId = (String) session.getAttribute("loginRoleId");
            Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
            if (null != coll){
                tokenUser = (UserInfoDTO) coll.getPrimaryPrincipal();
                tokenUser.setAuthToken(authToken);
            }
        } catch (Exception e) {
            log.info("根据token获取用户信息异常",e);
        }
        return tokenUser;
    }
}
